package com.springcloud.auth.scheduled;

import com.springcloud.auth.config.OauthConfig;
import com.springcloud.auth.utils.UserManageUtil;
import com.springcloud.auth.vo.TokenVo;
import com.springcloud.auth.utils.JedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description: 轮询检查用户是否在线
 * @author: hzl
 * @time: 2020/11/24 0024 9:59
 */
//@Component
public class UserManegeScheduledServer {

    private static final Logger logger = LoggerFactory.getLogger(UserManegeScheduledServer.class);

    @Resource
    private JedisUtil jedisUtil;

    /**
     * 可以设置轮询的时间,此处设置为15分钟清除一次
     */
    @Scheduled(cron = "0 0/15 * ? * *")
    public void scheduled() {
        logger.info("========轮询在线用户，清除数据======");

        if (UserManageUtil.userMap.size() == 0) {
            return;
        }

        //acToken过期视为用户下线
        Set<String> keys = jedisUtil.getKeys(OauthConfig.AUTH_ACCESS_TOKEN + "*");

        //拿到accToken 键值对
        Map<String, String> acTokenMap = new HashMap<>();
        for (String id : UserManageUtil.userMap.keySet()) {
            TokenVo tokenVo = UserManageUtil.getToken(id);
            acTokenMap.put(tokenVo.getAcToken(), id);
        }

        List<String> unExistUserIdList = new ArrayList<>();
        for (String acToken : acTokenMap.keySet()) {
            //是否存在该用户，存在，则记录
            String redisAcToken = OauthConfig.AUTH_ACCESS_TOKEN + acToken;
            boolean isExist = keys.contains(redisAcToken);
            if (!isExist) {
                String userId = acTokenMap.get(acToken);
                unExistUserIdList.add(userId);
            }
        }

        //移除不在线用户
        for (String unExistUserId : unExistUserIdList) {

            UserManageUtil.removeToken(unExistUserId);
        }

        logger.info("========轮询结束======");
    }
}
